use crate::{
    config::GameConfig, 
    render::Renderer, 
    localization::get_string,
    scene_manager::{SceneManager, Scene}, // 导入 Scene
    asset_manager::AssetManager,
};
use crossterm::{
    event::{self, Event, KeyCode},
    terminal::{self, EnterAlternateScreen, LeaveAlternateScreen},
    execute,
    style::{Color, SetBackgroundColor},
    cursor,
};
use std::io::{self, Write, stdout};
use std::time::{Duration, Instant};

pub struct GameEngine {
    pub running: bool,
    pub last_frame_time: Instant,
    pub frame_time: Duration,
    pub config: GameConfig,
    pub frame_counter: u32,
    pub last_fps_update: Instant,
    pub fps: f32,
    pub scene_manager: SceneManager,
    pub asset_manager: AssetManager,
}

impl GameEngine {
    pub fn show_splash_screen(&self) -> io::Result<()> {
        let mut stdout = stdout();
        
        // 进入全屏模式
        terminal::enable_raw_mode()?;
        execute!(stdout, EnterAlternateScreen)?;
        
        // 清屏并设置背景色
        let bg_color = Renderer::parse_color(&self.config.splash.background_color);
        let text_color = Renderer::parse_color(&self.config.splash.text_color);
        
        // 设置整个屏幕的背景色
        execute!(
            stdout,
            SetBackgroundColor(bg_color),
            terminal::Clear(terminal::ClearType::All),
        )?;

        // 获取终端大小
        let (width, height) = terminal::size()?;

        // 计算logo位置（居中）
        let logo_lines: Vec<&str> = self.config.splash.logo.lines().collect();
        let logo_height = logo_lines.len() as u16;
        let logo_width = logo_lines.iter().map(|l| l.len()).max().unwrap_or(0) as u16;
        
        let start_x = (width - logo_width) / 2;
        let start_y = (height - logo_height) / 2 - 2;

        // 绘制logo
        for (i, line) in logo_lines.iter().enumerate() {
            Renderer::draw_text(
                &mut stdout,
                line,
                start_x,
                start_y + i as u16,
                text_color,
                bg_color,
            )?;
        }

        // 绘制引擎标题
        let title = get_string("game_title", &self.config.language);
        Renderer::draw_text(
            &mut stdout,
            title,
            (width - title.len() as u16) / 2,
            start_y + logo_height + 1,
            text_color,
            bg_color,
        )?;

        // 绘制提示文本
        let press_key_text = if self.config.splash.press_key_text.is_empty() {
            get_string("press_any_key", &self.config.language)
        } else {
            &self.config.splash.press_key_text
        };
        
        Renderer::draw_text(
            &mut stdout,
            press_key_text,
            (width - press_key_text.len() as u16) / 2,
            height - 3,
            text_color,
            bg_color,
        )?;

        stdout.flush()?;
        Ok(())
    }

    pub fn wait_for_key(&mut self) -> io::Result<()> {
        loop {
            if event::poll(Duration::from_millis(100))? {
                if let Event::Key(_) = event::read()? {
                    break;
                }
            }
        }
        Ok(())
    }

    pub fn new(config: GameConfig) -> Result<Self, anyhow::Error> {
        let asset_dir = config.asset_dir.as_deref().unwrap_or("assets");
        
        let mut asset_manager = AssetManager::new();
        asset_manager.load_assets(asset_dir)?;
        
        let mut scene_manager = SceneManager::new();
        
        // 加载初始场景
        if let Some(scene_config) = asset_manager.get_scene_config(&config.initial_scene) {
            let mut scene = Scene::new(&scene_config.name);
            scene.load_from_config(scene_config, &asset_manager)?;
            scene_manager.add_scene(&scene.name, scene);
            scene_manager.current_scene = config.initial_scene.clone();
        }
        
        Ok(Self {
            running: true,
            last_frame_time: Instant::now(),
            frame_time: Duration::from_millis(33), // ~30 FPS
            config,
            frame_counter: 0,
            last_fps_update: Instant::now(),
            fps: 0.0,
            scene_manager,
            asset_manager,
        })
    }

    pub fn run(&mut self) -> io::Result<()> {
        let mut stdout = stdout();
        
        // 显示启动画面
        self.show_splash_screen()?;
        self.wait_for_key()?;
        
        // 主游戏循环
        terminal::enable_raw_mode()?;
        execute!(stdout, EnterAlternateScreen)?;
        
        // 初始化场景
        if let Some(scene) = self.scene_manager.get_current_scene() {
            for system in &mut scene.systems {
                system.init(scene);
            }
        }
        
        while self.running {
            let start_time = Instant::now();
            let delta_time = self.last_frame_time.elapsed().as_secs_f32();
            
            // 处理场景切换
            self.scene_manager.apply_scene_switch();
            
            // 处理输入
            self.handle_input()?;
            
            // 更新游戏状态
            if let Some(scene) = self.scene_manager.get_current_scene() {
                for system in &mut scene.systems {
                    system.update(scene, delta_time);
                }
            }
            
            // 开始渲染帧
            Renderer::begin_frame(&mut stdout)?;
            
            // 渲染游戏内容
            if let Some(scene) = self.scene_manager.get_current_scene() {
                // 渲染背景
                if let Some(bg) = &scene.background {
                    // 这里可以渲染背景
                }
                
                // 渲染实体
                for system in &scene.systems {
                    system.render(&mut stdout, scene);
                }
            }
            
            // 渲染UI
            self.render_ui(&mut stdout)?;
            
            // 结束帧
            Renderer::end_frame(&mut stdout)?;
            
            // 刷新输出
            stdout.flush()?;
            
            // 更新帧计数器
            self.frame_counter += 1;
            if self.last_fps_update.elapsed().as_secs_f32() >= 0.5 {
                self.fps = self.frame_counter as f32 / self.last_fps_update.elapsed().as_secs_f32();
                self.frame_counter = 0;
                self.last_fps_update = Instant::now();
            }
            
            // 控制帧率
            let elapsed = start_time.elapsed();
            if elapsed < self.frame_time {
                std::thread::sleep(self.frame_time - elapsed);
            }
            self.last_frame_time = start_time;
        }
        
        // 清理
        terminal::disable_raw_mode()?;
        execute!(stdout, LeaveAlternateScreen, cursor::Show)?;
        Ok(())
    }

    fn handle_input(&mut self) -> io::Result<()> {
        while event::poll(Duration::from_millis(10))? {
            if let Event::Key(key) = event::read()? {
                match key.code {
                    KeyCode::Esc | KeyCode::Char('q') => self.running = false,
                    _ => {}
                }
            }
        }
        Ok(())
    }

    fn render_ui(&self, stdout: &mut io::Stdout) -> io::Result<()> {
        // 获取终端大小
        let (width, height) = terminal::size()?;
        
        // 绘制游戏边框
        Renderer::draw_box(stdout, 0, 0, width, height, Color::White, Color::Black)?;
        
        // 绘制游戏标题
        let scene_name = if let Some(scene) = self.scene_manager.scenes.get(&self.scene_manager.current_scene) {
            scene.name.as_str()
        } else {
            "No Scene"
        };
            
        let title = format!("{}: {} - {}", 
            get_string("game_title", &self.config.language), 
            self.config.name,
            scene_name);
            
        Renderer::draw_text(stdout, &title, 2, 0, Color::Cyan, Color::Black)?;
        
        // 绘制控制提示
        let quit_hint = get_string("quit_hint", &self.config.language);
        Renderer::draw_text(stdout, quit_hint, width - quit_hint.len() as u16 - 2, 0, Color::Yellow, Color::Black)?;
        
        // 绘制状态信息
        let status = format!("{}: 100 | {}: {:.1}", 
            get_string("player_health", &self.config.language),
            get_string("fps", &self.config.language),
            self.fps);
        
        Renderer::draw_text(stdout, &status, 2, height - 1, Color::Magenta, Color::Black)?;
        
        Ok(())
    }
}